import 'package:flutter_live_data/live_data_export.dart';
import 'package:get/get.dart';

extension LiveDataExtend<T> on LiveData<T> {
  static String rxKey = 'get-rx';
  static String rxKeyNoNull = 'get-rx-no-null';

  Rx<T?> toRxOrNull(LifecycleOwner owner) {
    bool isNew = !extras.containsKey(rxKey);
    Rx<T?> rx = extras[rxKey] ??= Rx<T?>(value);
    if (isNew) {
      observe(owner, (it) {
        rx.value = it;
      });
    }
    return rx;
  }
  // 转换成Rx
  Rx<T> toRx(LifecycleOwner owner, T defaultValue) {
    bool isNew = !extras.containsKey(rxKeyNoNull);
    Rx<T> rx = extras[rxKeyNoNull] ??= Rx<T>(value ?? defaultValue);
    if (isNew) {
      observe(owner, (it) {
        rx.value = it;
      });
    }
    return rx;
  }

  //与 Rx 绑定，调用一次绑定一次,同一个rx不要调用多次
  void bindRx(LifecycleOwner owner, Rx<T> rx) {
    observe(owner, (it) {
      rx.value = it;
    });
  }
}
